import React, {Component} from 'react';
import NavHeader from "../../../../components/NavHeader/NavHeader";
import FilterFoot from "../../../../components/FilterFoot/FilterFoot";
import styles from './index.module.css'
import {NavLink} from "react-router-dom";
import {Icon, Picker, List, ImagePicker, Toast} from "antd-mobile";
import HeadPicker from "../../../HouseDetail/components/HeadPacker/HeadPicker";
import { require2,post} from "../../../../netWork";
import {getToken} from "../../../../utiles/token";


const district = [
    {
        "label": "一室",
        "value": "ROOM|d4a692e4-a177-37fd"
    },
    {
        "label": "二室",
        "value": "ROOM|d1a00384-5801-d5cd"
    },
    {
        "label": "三室",
        "value": "ROOM|20903ae0-c7bc-f2e2"
    },
    {
        "label": "四室",
        "value": "ROOM|ce2a5daa-811d-2f49"
    },

    {
        "label": "四室+",
        "value": "ROOM|2731c38c-5b19-ff7f"
    }
];
const floot = [
    {
        "label": "高楼层",
        "value": "FLOOR|1"
    },
    {
        "label": "中楼层",
        "value": "FLOOR|2"
    },
    {
        "label": "低楼层",
        "value": "FLOOR|3"
    }
];
const orientation = [
    {
        "label": "东",
        "value": "ORIEN|141b98bf-1ad0-11e3"
    },
    {
        "label": "南",
        "value": "ORIEN|61e99445-e95e-7f37"
    },
    {
        "label": "东南",
        "value": "ORIEN|dfb1b36b-e0d1-0977"
    },
    {
        "label": "北",
        "value": "ORIEN|caa6f80b-b764-c2df"
    },
    {
        "label": "西北",
        "value": "ORIEN|80795f1a-e32f-feb9"
    },
    {
        "label": "西",
        "value": "ORIEN|103fb3aa-e8b4-de0e"
    },
    {
        "label": "东北",
        "value": "ORIEN|67ac2205-7e0f-c057"
    },
    {
        "label": "西南",
        "value": "ORIEN|2354e89e-3918-9cef"
    }
];

const list = [
    "电视",
    "冰箱",
    "洗衣机",
    "空调",
    "热水器",
    "床",
    "暖气",
    "宽带",
    "衣柜",
    "天然气",

];
//暂存数据
var facilitiesList = [];
class RentAdd extends Component {
    state = {
        //存放户型数据
        froomType: [],
        //存放楼层
        ffloor: [],
        //存放朝向
        foriented: [],
        //存放图片
        houseImg: [],
        //存放房屋配置
        fsupporting: [],
        //房屋大小
        size: '',
        //房屋价格
        price: '',
        //小区
        community: '',
        //小区id
        communityId: '',
        //房屋标题
        title: '',
        //房屋描述
        description: '',
    };

    componentDidMount() {
        /*   console.log(this.props);*/
        const {id} = (this.props.match.params);
        const val = localStorage.getItem("community_val");
        if (id) {
            this.setState({community: val, communityId: id})
        } else return null
    }

    //租金
    getPrice = (e) => {
        const price = e.target.value;
        /*       console.log(price);*/
        this.setState({price})
    };
    //房屋大小
    getSize = (e) => {
        const size = e.target.value;
        this.setState({size})
    };
    //房屋标题
    getTitle = (e) => {
        const title = e.target.value;
        this.setState({title})
    };
    //房屋描述
    getDesc = (e) => {
        const description = e.target.value;
        this.setState({description})
    }
    //户型选中值
    districtVale = (val) => {
        this.setState({froomType: val});

    };
    //楼层选中值
    flootVal = (val) => {
        this.setState({ffloor: val});

    };
    //朝向选中值
    oriendVal = (val) => {
        this.setState({foriented: val});

    };

    //房屋图片
    imgChange = (files) => {
        this.setState({houseImg: files});
    };

    //获取图片路径
    getImgUrl = async () => {
        new Promise(resolve => {
            const {houseImg} = this.state;
            // console.log(houseImg);
            this.form = new FormData();
            if (houseImg.length > 0) {
                houseImg.forEach(item => this.form.append('file', item.file))
            }
            resolve()
        }).then(() => {
            console.log(this.form);
            require2({
                url: '/houses/image',
                headers: {"Content-Type": 'multipart/form-data'}, //请求头
                data: this.form
            }).then(res => {
                /*console.log(res);*/
                let img = res.body.join('|');
                // console.log(img);
                return new Promise(resolve => {
                    resolve(img)
                })
            }).then(img => {
                this.setState({houseImg:img})
                // houseImg = img
            })
        })
    };


    //promist
    promise = () => {
            let {houseImg} = this.state;
            // console.log(houseImg);
            this.form = new FormData();
            if (houseImg.length > 0) {
                houseImg.forEach(item => this.form.append('file', item.file))
            }
            require2({
                url: '/houses/image',
                headers: {"Content-Type": 'multipart/form-data'}, //请求头
                data: this.form
            }).then(res => {
                /*console.log(res);*/
                let img = res.body.join('|');
                return new Promise(resolve => {
                    resolve(img)
                }).then(ress =>{
                    console.log(ress);
                    this.send(ress)
                })
            })

    };

    //房屋配置
    onClicked = (item) => {
        let index = facilitiesList.indexOf(item);
        if (index !== -1) {
            facilitiesList.splice(index, 1)
        } else {
            facilitiesList.push(item)
        }
        this.setState({fsupporting: facilitiesList})
    };

    //确定发布
    Ok = () => {
              this.promise()
    };

    //发送请求

    send =  (ress) => {
        var {fsupporting} = this.state;
        const {price, communityId, description, foriented, title, size, froomType, ffloor} = this.state;
        let supporting = fsupporting.join('|');
        var tokenId = getToken();
        console.log('价格:',price, '城市:',communityId, '描述:',description,'朝向:', foriented, '标题L:',title, '大小,'.size, '类型:',froomType,
            '亮点:',supporting,'楼层:',ffloor);
        post({
            url: '/user/houses',
            headers: {authorization: tokenId},
            data: {
                'title': title,
                'description': description,
                'houseImg': ress,
                'orientation': foriented[0],
                'supporting': supporting,
                'price': price,
                'roomType': froomType[0],
                'size': size,
                'floor': ffloor[0],
                'community': communityId,
            },
        }).then(res => {
           if(res.status === 200){
            Toast.info('发布成功',1);
               this.props.history.push('/rent/rented')
           }
        })
    };

    render() {
        return (
            <div className={styles.root_root}>
                <div className={styles.root}>
                    <div className={styles.nav}>
                        <NavHeader className={styles.navheader} rightContent={ <Icon key="1" type="ellipsis" />}>发布房源</NavHeader>
                    </div>
                    <div className={styles.mesg}>房源信息</div>
                    <div className={styles.houseinfo}>
                        小区名称
                        <NavLink to='/rent/search' className={styles.link}>
                            <input type="text" className={styles.input} value={this.state.community} name='community'
                                   placeholder='请选择'/>
                            <Icon type="right" className={styles.span} color='#c8c8c8'/>
                        </NavLink>
                    </div>
                    <div className={styles.houseinfo}>
                        <span className={styles.rent}>租</span>金
                        <input type="text" className={styles.input1} name='price' placeholder='请输入租金/月'
                               onBlur={(e) => this.getPrice(e)}/>
                        <span className={styles.ff}>￥/月</span>
                    </div>
                    <div className={styles.houseinfo}>
                        <span>建筑面积</span>
                        <input type="text" className={styles.input1} name='size' placeholder='请输入建筑面积'
                               onBlur={(e) => this.getSize(e)}/>
                        <span className={styles.ff}>m²</span>
                    </div>
                    <Picker data={district} cols={1} className="forss"
                            extra="请选择"
                            itemStyle={{fontSize: '14px'}}
                            value={this.state.froomType}
                            onChange={val => this.districtVale(val)}
                    >
                        <List.Item arrow="horizontal"
                                   style={{
                                       borderBottom: 'solid',
                                       borderBottomColor: 'whitesmoke',
                                   }}>户<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>型</List.Item>
                    </Picker>
                    <Picker data={floot} cols={1} className={styles.forss}
                            itemStyle={{fontSize: '14px'}}
                            extra="请选择"
                            value={this.state.ffloor}
                            onChange={val => this.flootVal(val)}>
                        <List.Item arrow="horizontal"
                                   style={{borderBottom: 'solid', borderBottomColor: 'whitesmoke'}}>所在楼层</List.Item>
                    </Picker>
                    <Picker data={orientation} cols={1} className="forss"
                            itemStyle={{fontSize: '14px'}}
                            extra="请选择"
                            value={this.state.foriented}
                            onChange={val => this.oriendVal(val)}>
                        <List.Item arrow="horizontal"
                                   style={{
                                       borderBottom: 'solid',
                                       borderBottomColor: 'whitesmoke'
                                   }}>朝<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>向</List.Item>
                    </Picker>
                    <div className={styles.room_title_drive}>
                        <div className={styles.title}>房屋标题</div>
                        <textarea className={styles.inputdesc} name='title'
                                  placeholder='请输入标题（例如： 整租 小区名 2室 5000元）'
                                  onBlur={e => this.getTitle(e)}/>
                    </div>
                    {/*房屋图片*/}
                    <div className={styles.room_title_drive}>
                        <div className={styles.title}>房屋图像</div>
                        <ImagePicker
                            files={this.state.houseImg}
                            onImageClick={(index, fs) => console.log(index, fs)}
                            multiple={true}
                            onChange={this.imgChange}
                        />
                    </div>
                    {/*房屋配置*/}
                    <div className={styles.room_title_drive}>
                        <div className={styles.title}>房屋配置</div>
                        <HeadPicker list={list}
                                    onClicked={this.onClicked}
                                    className={styles.headpicker}
                                    isFacilities={this.state.fsupporting}/>
                    </div>
                    {/*房屋描述*/}
                    <div className={styles.room_title_drive}>
                        <div className={styles.title}>房屋描述</div>
                        <textarea className={styles.inputdesc}
                                  placeholder='请输入描述（例如： 交通，环境）'
                                  onBlur={e => this.getDesc(e)}/>
                    </div>
                </div>
                <FilterFoot className={styles.foot} onText='取消' onCancle={this.canCle} onOk={this.Ok}>提交</FilterFoot>
            </div>
        );
    }
}

export default RentAdd;
